﻿using System;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;

namespace objectOutlet.Umbraco.ConnectedPages.Config
{
	[Serializable]
	internal class ConnectedPagesConfig
	{
		[NonSerialized]
		private const string CacheName = "objectOutletUmbracoConnectedPages.config";
		[NonSerialized]
		private const string VirtualPath = "~/config/ConnectedPages.config";

		public string[] IgnorePropertyAlias { get; private set; }
		public string RelationTypeAlias { get; private set; }
		public bool RethrowExceptions { get; private set; }
		public bool SaveAsCurrentUser { get; private set; }
		public bool ShowIconOverlays { get; private set; }
		
		private ConnectedPagesConfig()
		{
			IgnorePropertyAlias = new string[] { };
			RelationTypeAlias = "relateDocumentOnCopy";
			RethrowExceptions = true;
			SaveAsCurrentUser = false;
			ShowIconOverlays = true;
		}

		// TODO: Skal nok laves som en contract, da jeg ikke tror vi vil have public setters på properties her

		public static ConnectedPagesConfig Current
		{
			get
			{
				var cfg = HttpContext.Current.Cache[CacheName] as ConnectedPagesConfig;
				if (cfg != null)
					return cfg;

				var path = HostingEnvironment.MapPath(VirtualPath);
				if (path == null)
					return new ConnectedPagesConfig();

				if (!File.Exists(path))
				{
					cfg = new ConnectedPagesConfig();
					Helpers.Serialization.SerializeXmlObjectToFile(typeof(ConnectedPagesConfig), cfg, path);
				}
				else
				{
					cfg = (ConnectedPagesConfig)Helpers.Serialization.DeserializeXmlObjectFromFile(path, typeof(ConnectedPagesConfig));
				}

				HttpContext.Current.Cache.Insert(CacheName, cfg, new CacheDependency(path));

				return cfg;
			}
		}
	}
}